package com.chen.springbootweb.controller;

import com.chen.springbootweb.entity.User;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

@RestController
public class UserController {

    @RequestMapping("/getUser")
    public User getUser(){
        User user = new User();
        user.setName("admin");
        user.setAge(24);
        user.setPassword("123456");

        return user;
    }

    @RequestMapping("/getUserList")
    public List<User> getUserList(){
        List<User> list = new ArrayList<>();
        for (int i = 0; i < 2; i++) {
            User user = new User();
            user.setName("张"+i);
            user.setAge(20 + i);
            user.setPassword("123456");
            list.add(user);
        }
        return list;
    }

    @PostMapping("/saveUser")
    public void saveUser(@Valid User user, BindingResult result){
        System.out.println("user"+ user) ;
        if (result.hasErrors()){
            List<ObjectError> list = result.getAllErrors();
            for (ObjectError error:list){
                System.out.println(error.getCode()+"-"+error.getDefaultMessage());
            }
        }
    }
}
